import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ResourceEntity } from './resource.entity';
import { CreateResourceDto, UpdateResourceDto } from './dto';
import { ResourceMessage } from './resource.message';
import { validate } from 'class-validator';
import { HttpStatus } from '@nestjs/common';
import { ResponseData } from '../shared/base.interface';
import { ResponseCode } from '../shared/base.responseCode';

const R = require('ramda');

@Injectable()
export class ResourceService {
  constructor(
    @InjectRepository(ResourceEntity)
    private readonly resourceRepository: Repository<ResourceEntity>,
  ) {}

  async findAll(): Promise<ResponseData> {
    const result = await this.resourceRepository.find();
    return {
      code: ResponseCode.ok,
      message: '',
      data: result,
    };
  }

  async create(dto: CreateResourceDto): Promise<ResponseData> {
    const result = await this.resourceRepository.save(dto);
    return {
      code: ResponseCode.ok,
      message: '',
      data: result,
    };
  }

  async update(dto: UpdateResourceDto): Promise<ResponseData> {
    const updatedResource = await this.resourceRepository.save(dto);
    return {
      code: ResponseCode.ok,
      message: '',
      data: updatedResource,
    };
  }

  async delete(id: number): Promise<ResponseData> {
    const resourceList = await this.resourceRepository.find();
    if (!resourceList && resourceList.length === 0) {
      return {
        code: ResponseCode.fail,
        message: '',
      };
    }
    const deleteIds: number[] = [];
    resourceList.forEach(item => {
      if (item.id === id || item.parentId === id) {
        deleteIds.push(item.id);
      }
    });
    if (!deleteIds.length) {
      return {
        code: ResponseCode.fail,
        message: '',
      };
    }
    const deleteResult = await this.resourceRepository.delete(deleteIds);
    if (deleteResult.affected === 0) {
      return {
        code: ResponseCode.fail,
        message: '',
      };
    }
    return {
      code: ResponseCode.ok,
      message: '',
    };
  }
}
